<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product extends AdminBase {
	public function __construct()
    {
        parent::__construct();
    }

	public function index($p=1)
	{
		$container = 15;
		$search = $this->input->get('search');
		$this->db->from('product');
		if(!empty($search)){
			$this->db->like('title',$search);
		}
		$count = $this->db->count_all_results();
		$ps = ceil($count/$container);
		if($p<1||$p>$ps){
			$list = [];
		}else{
			if(!empty($search)){
				$this->db->like('title',$search);
			}
			$this->db->select('product.id,product.name,product.thumb,admin_users.name as user,location.name as location,product.uri,host.name as host,product.update_at,product.created_at');
			$this->db->limit($container, ($p-1)*$container);
			$this->db->order_by('product.id', 'DESC');
			$this->db->join('admin_users', 'product.admin_id = admin_users.id');
			$this->db->join('location', 'product.location_id = location.id');
			$this->db->join('host', 'product.host_id = host.id');
			$list = $this->db->get('product')->result_array();
		}
		$pagenation = '';
		if($ps>1){
			$pagenation .='<nav aria-label="Page navigation pull-right"><ul class="pagination">';
			for ($i=1; $i<=$ps; $i++){
				if($i==1){
					$disabled = $p==1?' class="disabled"':'';
					$preUrl = $p==1?'#':site_url("admin/product/index/".($p-1));
					$pagenation .='<li'.$disabled.'><a href="'.$preUrl.'" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>';
				}
				$active = $i==$p?' class="active"':'';
				$pagenation .='<li'.$active.'><a href="'.site_url("admin/product/index/".$i).'">'.$i.'</a></li>';
				if($i==$ps){
					$disabled = $p==$ps?' class="disabled"':'';
					$nextUrl = $p==$ps?'#':site_url("admin/product/index/".($p+1));
					$pagenation .='<li'.$disabled.'><a href="'.$nextUrl.'" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>';
				}
			}
			$pagenation .='</ul></nav>';
		}

        
		$this->admin_view('product_list','商品列表',[
			'list' => $list,
			'pagenation'=>$pagenation,
			'search'=>empty($search)?'':$search
		]);
	}
	public function form($id=0)
	{
		$data = [];
		$title = '商品上新';
		if($id!=0){
			$product = $this->db->get_where('product', array('id' => $id))->row_array();
			if(!$product) return $this->admin_message('商品不存在！','danger');
			$data['product']=$product;
			$title = '商品编辑';
		}
		$this->db->start_cache();
		$this->db->order_by('order','ASC');
		$this->db->select('id, name');
		$this->db->stop_cache();
        $data['location'] = $this->db->get('location')->result_array();
        $data['host'] = $this->db->get('host')->result_array();
        $this->db->flush_cache();
        $data['theme'] = getThemes();
		$this->admin_js(['/static/addon/uediter/ueditor.config.js','/static/addon/uediter/ueditor.all.min.js']);
		$this->admin_view('product_form',$title,$data);
	}

	public function ajax_form(){
		$post = $this->input->post();
		$error = self::productEx($post);
		if($error){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>$error)));
				return;
		}
		$this->db->where('uri', $post['uri']);
		$this->db->where('host_id', $post['host_id']);
		if($post['id']) $this->db->where('id !=', $post['id']);;
		$uri = $this->db->get('product')->row_array();
		if($uri){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'商品链接已存在！')));
				return;
		}
		if($post['id']){
			$this->db->where('id', $post['id']);
			$post['update_at'] = date("Y-m-d H:i:s");
			if($bool = $this->db->update('product',$post)){
				$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'ok','message'=>'修改成功！')));
				return;
			}
		}else{
			$user = $this->db->get_where('admin_users',array('username' => $this->session->name))->row();
			$post['admin_id'] = $user['id'];
			$post['created_at'] = date("Y-m-d H:i:s");
			if($this->db->insert('product',$post)){
				$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'ok','message'=>'添加成功！')));
				return;
			}
		}
		$this->output->set_content_type('application/json')
			 ->set_output(json_encode(array('statu' => 'failed','message'=>'系统错误！')));
			return;
	}

	

	public function delete(){
		$id = $this->input->post('id');
		$bool = $this->db->delete('product',array('id'=>$id));
		if($bool){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'ok','message'=>'删除成功！')));
				return;
		}else{
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'删除失败！')));
				return;
		}
	}

	public function checkurl(){
		$post = $this->input->post();
		if(!preg_match("/^([.a-zA-Z0-9_-]{1,50})$/",$post['uri'])){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'二级域名不合法！')));
				return;
		}
		$this->db->where('uri', $post['uri']);
		$this->db->where('host_id', $post['host_id']);
		if(isset($post['id'])) $this->db->where('id !=', $post['id']);;
		$product = $this->db->get('product')->row_array();
		if($product){
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'failed','message'=>'产品链接已存在！')));
				return;
		}else{
			$this->output->set_content_type('application/json')
				 ->set_output(json_encode(array('statu' => 'ok','message'=>'可以使用！')));
				return;
		}
	}

	private function productEx($post){
		if(!$post['uri']) return '二级域名不能为空！';
		if(!$post['name']) return '商品中文名称不能为空！';
		if(!$post['title']) return '标题不能为空！';
		if(!$post['price_base']||$post['price_base']==0) return '请填写原价！';
		if(!$post['price']||$post['price']==0) return '请填写售价！';
		if(!$post['thumb']||$post['thumb']=='[]') return '请上传缩略图！';
		if(!$post['img_banners']||$post['img_banners']=='[]') return '请上传展示图！';

		if(mb_strlen($post['name'],"UTF8")<1 || mb_strlen($post['name'],"UTF8")>30) return '商品中文名称长度为1-30个字符！';
		if(mb_strlen($post['title'],"UTF8")<1 || mb_strlen($post['title'],"UTF8")>30) return '标题长度为1-30个字符！';
		if(mb_strlen($post['content'],"UTF8")>3000) return '商品详情超过3000个字符！';
		if(!preg_match("/^([.a-zA-Z0-9_-]{1,50})$/",$post['uri'])) return 'url不合法！';
		if($post['price']<0 || $post['price']>100000) return '价格超出范围！';
		if($post['price_base']<0 || $post['price_base']>100000) return '价格超出范围！';
		if($post['price']>$post['price_base']) return '售价不能大于原价！';
		return false;
	}
	

}